package com.cf.work;

import com.cf.utils.ConnectionUtil;
import com.rabbitmq.client.*;

import java.io.IOException;

/**
 * work 工作模式
 *
 * @author Chengfei
 * @date 2020/8/29 15:08
 */
public class Consumer2 {


    public static void main(String[] args) throws Exception {

        //2. 连接对象
        Connection connection = ConnectionUtil.getConnection();
        //3.创建频道
        Channel channel = connection.createChannel();

        channel.queueDeclare(Produce.QUEUE_NAME,true,false,false,null);

        //一次只能接受并处理一个消息
        channel.basicQos(1);

        //创建消费者,并设置消息处理
        DefaultConsumer consumer = new DefaultConsumer(channel){
            @Override
            /**
             * consumerTag 消息者标签，在channel.basicConsume时候可以指定
             * envelope 消息包的内容，可从中获取消息id，消息routingkey，交换机，消息和重传标志(收到消息失败后是否需要重新发送)
             * properties 属性信息
             * body 消息
             */
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                //路由key
                System.out.println("路由key为：" + envelope.getRoutingKey());
                //交换机
                System.out.println("交换机为：" + envelope.getExchange());
                //消息id
                System.out.println("消息id为：" + envelope.getDeliveryTag());
                //收到的消息
                System.out.println("接收到的消息为：" + new String(body, "utf-8"));

                try {
                    Thread.sleep(1000);

                    //确认消息
                    channel.basicAck(envelope.getDeliveryTag(),false);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };

        //channel.basicConsume("", true, consumer);
        channel.basicConsume(Produce.QUEUE_NAME, false, consumer);
        //6 不关闭资源
        //channel.close();
        //connection.close();

    }
}
